package org.will.http.config;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.will.http.CBHttpLogFactory;
import org.will.http.domain.CBHttpProxy;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author wangwei-ww
 * @Date 2017/3/30 10:50
 * @Comment
 */
public class CBHttpHandlerConfig {
    private String proxyConfigs; // 配置代理地址，格式：ip:port:account:password,ip:port...
    private String measureURL = "https://mws.amazonservices.com"; // 配置测速URL
    private long measureInterval = 1000 * 60; // 检测间隔,默认1min
    private boolean autoMeasure = false;
    private final String hostSpliter = ",", portSpliter = ":";

    public String getProxyConfigs() {
        return proxyConfigs;
    }

    public String getMeasureURL() {
        return measureURL;
    }

    public long getMeasureInterval() {
        return measureInterval;
    }

    public boolean isAutoMeasure() {
        return autoMeasure;
    }

    public void setProxyConfigs(String proxyConfigs) {
        this.proxyConfigs = proxyConfigs;
    }

    public void setMeasureURL(String measureURL) {
        this.measureURL = measureURL;
    }

    public void setMeasureInterval(long measureInterval) {
        this.measureInterval = measureInterval;
    }

    public void setAutoMeasure(boolean autoMeasure) {
        this.autoMeasure = autoMeasure;
    }

    public List<CBHttpProxy> parseProxyConfg() {
        List<CBHttpProxy> proxys = new ArrayList<>();
        String[] hostInfos = getProxyConfigs() == null ? null : getProxyConfigs().split(hostSpliter);
        if (ArrayUtils.isEmpty(hostInfos)) {
            return proxys;
        }

        for (String hostInfoStr : hostInfos) {
            String[] hostInfo = hostInfoStr.split(portSpliter);
            if (hostInfo.length >= 2 && StringUtils.isNumeric(hostInfo[1])) {
                CBHttpProxy proxy = new CBHttpProxy();
                proxy.setHost(hostInfo[0]);
                proxy.setPort(Integer.parseInt(hostInfo[1]));
                proxy.setUsername(hostInfo.length > 2 ? hostInfo[2] : null);
                proxy.setPassword(hostInfo.length > 3 ? hostInfo[3] : null);
                proxys.add(proxy);
            }
        }
        CBHttpLogFactory.getLogger().info("configs {}", getProxyConfigs());

        return proxys;
    }
}
